<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>终端列表</title>
    <meta name="ctx" th:content="${#httpServletRequest.getContextPath()}"/>
    <link rel="stylesheet" th:href="@{/css/admin/base-v2.css}">
    <link rel="stylesheet" th:href="@{/lib/flatpickr/flatpickr.min.css}">
    <link rel="stylesheet" th:href="@{/lib/font-awesome/4.7.0/css/font-awesome.min.css}">
    <link rel="stylesheet" th:href="@{/css/admin/app.css}">
    <style>
        .margin {
            margin-right: 15px;
        }
        /*2018.10.15头部修改form样式*/
        .form-item select{
            width: 84px;
        }
        .z-mal {
            margin-left: 10px;
            flex: 1;
        }
        .app-page-content .filter-group {
            flex-wrap: nowrap;
        }
        .app-page-content .filter-group .filter-item {
            /*max-width: none;*/
        }
        .float-right {
            text-align: right;
        }
    </style>
</head>

<body>
<div class="app-page" v-cloak id="app">
    <div class="app-page-content">
        <div class="app-card">
            <div class="app-card-body">
                <div class="app-card-body-con">
                    <!-- 过滤器 -->
                    <form class="filter">
                        <div class="filter-group">
                            <div class="j-option-switch filter-item">
                                <div class="option form-item" style="width: 84px; flex: 0">
                                    <select id="searchType" name="searchType" data-content-selector=".search">
                                        <option value="machineNumber">机器码</option>
                                        <option value="propertyName">小区名称</option>
                                        <option value="administrator">管理人</option>
                                    </select>
                                </div>
                                <div class="content z-mal">
                                </div>
                            </div>

                            <!-- 选项切换 -->
                            <div class="filter-item">
                                <div class="form-item row">
                                    <div class="label"><label>行政区</label></div>
                                    <div class="flex1">
                                        <select id="district" name="district">
                                            <option value="">全部</option>
                                            <option v-for="resultList in districtList " :value="resultList.district">
                                                {{resultList.district}}
                                            </option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="filter-item">
                                <div class="form-item row">
                                    <div class="label"><label>在线状态</label></div>
                                    <div class="flex1">
                                        <select id="onlineStatus" name="onlineStatus">
                                            <option value="">全部</option>
                                            <option value="0"  th:selected="${onlineStatus eq 0}">在线</option>
                                            <option value="1"  th:selected="${onlineStatus eq 1}">离线</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="filter-group">
                            <div class="filter-item">
                                <div class="form-item row">
                                    <div class="label"><label>设备状态</label></div>
                                    <div class="flex1">
                                        <select id="deviceStatus" name="deviceStatus">
                                            <option value="">全部</option>
                                            <option value="0" th:selected="${deviceStatus eq 0}">可售</option>
                                            <option value="1" th:selected="${deviceStatus eq 1}">预拆除</option>
                                            <option value="2" th:selected="${deviceStatus eq 2}">维护</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="filter-item">
                                <div class="form-item row">
                                    <div class="label"><label>固件版本</label></div>
                                    <div class="body">
                                        <input type="text" name="firmwareVersion" >
                                    </div>
                                </div>
                            </div>
                            <div class="filter-item">
                                <div class="form-item row">
                                    <div class="label"><label>APK版本</label></div>
                                    <div class="body">
                                        <input type="text" name="softwareVersion" >
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="filter-group text-align-right">
                            <div class="filter-item">
                                <div class="z-btn-group" style="max-width: 1060px;">
                                    <a class="z-btn z-primary" @click="initData(1,10)">查询</a>
                                    <a id="export-device-info" class="z-btn z-primary" @click="exportData()">导出</a>
                                </div>
                            </div>
                        </div>
                    </form>

                    <!-- 关联的选项 -->
                    <div class="search z-hide">
                        <div>
                            <div class="form-item">
                                <input type="text" placeholder="请输入查询机器码" id="machineNumber" name="machineNumber"
                                       maxlength="50">
                            </div>
                        </div>
                        <div>
                            <div class="form-item">
                                <input type="text" placeholder="请输入查询小区名称" id="propertyName" name="propertyName"
                                       maxlength="50">
                            </div>
                        </div>
                        <div>
                            <div class="form-item">
                                <input type="text" placeholder="请输入查询管理人" id="administrator" name="administrator"
                                       maxlength="50">
                            </div>
                        </div>
                    </div>
                    <!-- 关联的选项 End -->
                </div>
            </div>
        </div>

        <div class="app-card">
            <div class="app-card-body">
                <div class="app-card-body-con">

                    <div class="z-btn-group">
                        <button data-state="4" class="j-btn-control z-btn z-default">远程关机</button>
                        <button data-state="3" class="j-btn-control z-btn z-default">定时开关机</button>
                        <button data-state="1" class="j-btn-control z-btn z-default">重启终端</button>
                        <button data-state="0" class="j-btn-control z-btn z-default">音量设置</button>
                        <button data-state="5" class="j-btn-control z-btn z-default">管理授权</button>
                        <!--<button data-state="6" class="j-btn-control z-btn z-default">SIM卡启用</button>
                        <button data-state="7" class="j-btn-control z-btn z-default">SIM卡关停</button>-->
                        <button data-state="8" class="j-btn-control z-btn z-default">测速</button>
                    </div>

                    <div class="container z-df">
                        <div style="overflow: auto;">
                            <table class="z-table" style="width: 1500px">
                            <thead>
                                <th style="width:2%">
                                    <input type="checkbox" class="input" @click="onCheckboxAll" v-model="checkboxAll">
                                </th>
                                <th style="width:7%">机器码</th>
                                <th style="width:4%">在线状态</th>
                                <th style="width:4%">设备状态</th>
                                <th style="width:5%">SIM卡状态</th>
                                <th style="width:11%">最近访问时间</th>
                                <th style="width:5%">APK版本</th>
                                <th style="width:15%">固件版本</th>
                                <th style="width:5%">当月流量预警(MB)</th>
                                <th style="width:6%">行政区</th>
                                <th style="width:6%">小区名称</th>
                                <th style="width:8%">管理人</th>
                                <th style="width:13%">操作</th>
                            </thead>
                            <tbody>
                            <tr v-for="resultList in deviceList " :data-device-code="resultList.deviceCode"
                                :data-administrator-ids="resultList.administratorIds">
                                <td><input type="checkbox" class="input j-checkbox" v-model="resultList.checkbox"></td>
                                <td><a :href="'deviceDetail/' + resultList.deviceId" class="layer-open"
                                       data-title="终端详情">{{resultList.machineNum}}</a></td>
                                <td>{{resultList.onlineStatus}}</td>
                                <td>{{resultList.deviceStatus}}</td>
                                <td>{{resultList.simStatus}}</td>
                                <td>{{resultList.lastReportTime}}</td>
                                <td>{{resultList.softwareVersion}}</td>
                                <td>{{resultList.firmwareVersion}}</td>
                                <td>{{resultList.currentMonthTraffic}}</td>
                                <td>{{resultList.district}}</td>
                                <td>{{resultList.propertyName}}</td>
                                <td>
                                        <span v-for="userList in resultList.administrator"
                                              :data-user-id="userList.userId">
                                            <a class="user-info" data-title="联系信息" @click="showUserInfo(userList)">
                                                <span>{{userList.realname}}&nbsp&nbsp</span>
                                            </a>
                                        </span>
                                </td>
                                <td>
                                    <a :href="'deviceLogList?deviceCode=' + resultList.deviceCode" class="layer-open"
                                       data-title="日志">日志</a>
                                    <a class="authority-open" data-title="管理授权"
                                       @click="openAuthorityWindow(resultList)">管理授权</a>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                        </div>
                    </div>

                    <!-- 分页信息 -->
                    <div class="table-info z-pat z-fl">
                        总计：<p class="total margin">{{totalCount}}</p>在线：<p class="online margin">{{onLineDeviceCount}}</p>离线：<p
                            class="offline margin">{{offLineDeviceCount}}</p>
                    </div>
                    <div class="app-card-body">
                        <!-- 前端分页 -->
                        <div class="pagination z-pat z-fr"></div>
                    </div>

                </div>
            </div>
        </div>
    </div>


    <!-- 设备操作 -->
    <div class="popup-default z-popup z-fixed z-df z-flex-cc z-hide">
        <div class="bg" data-popup-close></div>
        <!-- 音量设置 -->
        <div class="popup-device-sound section z-hide">
            <div class="title">音量设置</div>
            <div class="content">
                <form>
                    <input type="hidden" name="deviceCodeSound" id="deviceCodeSound">
                    <div class="form-item row">
                        <div class="label">
                            <label>音量值</label>
                        </div>
                        <div class="body">
                            <input type="text" min="0" max="100" oninput="checkVolume(this)" name="deviceVolume"
                                   id="deviceVolume" value="">
                            0~100
                        </div>
                    </div>
                </form>
                <div class="z-btn-group">
                    <a class="z-btn z-primary" onclick="setVolume()">确定</a>
                    <a class="z-btn z-default" data-popup-close>取消</a>
                </div>
            </div>
        </div>
        <!-- 电源 -->
        <div class="popup-device-power section z-hide">
            <div class="title">开关机设置</div>
            <div class="content">
                <form>
                    <input type="hidden" name="deviceCodePower">
                    <div class="form-item row">
                        <div class="label">
                            <label>开机时间</label>
                        </div>
                        <div class="body">
                            <input type="datetime" name="bootTimePower" class="ft-hour" value="00:00">
                        </div>
                    </div>
                    <div class="form-item row">
                        <div class="label">
                            <label>关机时间</label>
                        </div>
                        <div class="body">
                            <input type="datetime" name="offTimePower" class="ft-hour" value="00:00">
                        </div>
                    </div>
                </form>
                <div class="z-btn-group">
                    <a class="z-btn z-primary" onclick="setTimerShutDownOrStart()">确定</a>
                    <a class="z-btn z-default" data-popup-close>取消</a>
                </div>
            </div>
        </div>
        <!-- 管理授权 -->
        <div class="popup-device-authority section z-hide">
            <div class="title">管理授权</div>
            <div class="content">
                <form>
                    <input type="hidden" name="deviceCodes" id="deviceCodes">
                    <div class="form-item row">
                        <div class="label">
                            <label>可选用户</label>
                        </div>
                        <div class="users body">
                        </div>
                    </div>
                    <div class="z-btn-group" style="margin-top:30px">
                        <a class="z-btn z-primary" onclick="deviceAuthority()">确定</a>
                        <a class="z-btn z-default" data-popup-close>取消</a>
                    </div>
                </form>
            </div>
        </div>
        <!-- 显示用户信息 -->
        <div class="popup-userInfo section z-hide">
            <div class="body">
                <div class="title">用户信息</div>
                <div class="userInfo body">
                    <div class="z-btn-group">
                        <a class="z-btn z-default" data-popup-close>取消</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script th:src="@{/lib/jquery.min.js}"></script>
<script th:src="@{/js/admin/app.js}"></script>
<script th:src="@{/lib/layer-v3.1.1/layer/layer.js}"></script>
<script th:src="@{/js/popup.js}"></script>
<script th:src="@{/js/form.js}"></script>
<script th:src="@{/js/admin/app.js}"></script>
<script th:src="@{/lib/flatpickr/flatpickr.js}"></script>
<script th:src="@{/js/tree.js}"></script>
<script th:src="@{/js/pagination.js}"></script>
<script th:src="@{/lib/vue/v2.5.16/vue.min.js}"></script>
<script th:src="@{/js/prompt.js}"></script>
<script th:src="@{/js/table.js}"></script>

<script>

    //获取context path
    var context = $("meta[name='ctx']").attr("content") || '';

    // 使用vue渲染页面
    var app = new Vue({
        el: '#app',
        data: {
            deviceList: [],
            districtList: [],
            onLineDeviceCount:0,
            offLineDeviceCount:0,
            totalCount:0,
            checkboxAll: false,
        },
        methods: {
            onCheckboxAll: function () {
                var deviceList = this.deviceList;

                var checkboxAll = this.checkboxAll;
                deviceList.map(function (item) {
                    item.checkbox = !checkboxAll;
                })

                this.deviceList = [...deviceList];
                ;
            }
        }
    });

    //从后台取到分页信息
    var currentPage = [[${pageNum}]];
    var pageSize =[[${pageSize}]];

    // 初始化分页控件（分页默认参数）
    var pagination = new Pagination(".pagination", {
        pageIndex: currentPage || 1, // 初始化页数
        pageSize: pageSize || 10, // 初始化每页条数
        count: 10, // 初始化总记录数（这样写相当于页面首次初始化加载时就展示了第一页）
        maxButtonCount: 5, // 分页按钮数量(可选)
        // 分页切换事件
        onPageChanged: function (pageIndex) { // 切换到指定分页
            console.log(pageIndex + "^" +pageSize);
            initData(pageIndex, pageSize);
        }
    })

    // 加载select联动内容
    $('[name="searchType"] option').each(function (index, element) {
        if ((App.query.searchType === undefined && index === 0) || App.query.searchType == $(this).val()) {
            $('.j-option-switch .content').html($(".search").children('div').eq(index).html())
        }
    })


    // 从URL加载搜索数据
    $(".filter").formLoad(App.query);

    // 获取表格中选择的设备Mac
    function getSelectedDevice() {
        let temp = [];
        $('tbody [type="checkbox"]').each(function (index, element) {
            if (element.checked == true) {
                temp.push($(this).parents('tr,.tr').data('deviceMac'));
            }
        })
        return temp.join(',');
    }

    /**
     * 创建参数字符串
     * @param pageIndex 当前页
     * @param pageSize 每页条数
     * @returns {string} 参数字符串
     */
    function createParamStr(pageIndex, pageSize) {
        var machineNumber = $("input[name='machineNumber']").val();
        var propertyName = $("input[name='propertyName']").val();
        var deviceMac = $("input[name='deviceMac']").val();
        var deviceIp = $("input[name='deviceIp']").val();
        var administrator = $("input[name='administrator']").val();
        var district = $("select[name='district']").val();
        var onlineStatus = $("select[name='onlineStatus']").val();
        var deviceStatus = $("select[name='deviceStatus']").val();
        var searchType = $("select[name='searchType']").val();
        var softwareVersion = $("input[name='softwareVersion']").val();
        var firmwareVersion = $("input[name='firmwareVersion']").val();

        var url = "";
        if (!isBlank(pageIndex)) {
            url = url + "&pageNum=" + pageIndex;
        }
        if (!isBlank(pageSize)) {
            url = url + "&pageSize=" + pageSize;
        }
        if (!isBlank(machineNumber)) {
            url = url + "&machineNumber=" + machineNumber;
        }
        if (!isBlank(propertyName)) {
            url = url + "&propertyName=" + propertyName;
        }
        if (!isBlank(deviceMac)) {
            url = url + "&deviceMac=" + deviceMac;
        }
        if (!isBlank(deviceIp)) {
            url = url + "&deviceIp=" + deviceIp;
        }
        if (!isBlank(administrator)) {
            url = url + "&administrator=" + administrator;
        }
        if (!isBlank(district)) {
            url = url + "&district=" + district;
        }
        if (!isBlank(onlineStatus)) {
            url = url + "&onlineStatus=" + onlineStatus;
        }
        if (!isBlank(deviceStatus)) {
            url = url + "&deviceStatus=" + deviceStatus;
        }
        if (!isBlank(searchType)) {
            url = url + "&searchType=" + searchType;
        }
        if (!isBlank(firmwareVersion)) {
            url = url + "&firmwareVersion=" + firmwareVersion;
        }
        if (!isBlank(softwareVersion)) {
            url = url + "&softwareVersion=" + softwareVersion;
        }
        console.log(url);
        return url;
    }

    //检查参数
    function isBlank(param) {
        if (undefined === param) {
            return true;
        }
        if (null == param) {
            return true;
        }
        if ("" === param) {
            return true;
        }
        return false;
    }

    var exportData=function(){
        var url = context + "/deviceInfo/exportDeviceList";
        var paramStr = createParamStr("", "");
        if (paramStr !== "") {
            paramStr = paramStr.substring(1);
            url = url + "?" + paramStr;
        }
        window.location.href = url;

    };

    // 管理员信息 - 弹窗打开
    var showUserInfo = function (data) {
        $('.userInfo').html("");
        // ajax查询用户信息
        App.ajax({
            type: "POST",
            data: {userId: data.userId},
            url: context + "/deviceInfo/getAuthorityUserInfo",
            success: function (obj) {
                var code = obj.code;
                if (code == 0) {
                    var data = obj.data;
                    var html = [];
                    html.push('<form> ' +
                        '       <input type="hidden" name="userId"> ' +
                        '           <div class="form-item row"> ' +
                        '               <div class="label"><label>联系电话</label></div>' +
                        '               <div class="body">' + data[0].mobilePhone + ' </div>' +
                        '           </div>' +
                        '           <div class="form-item row">' +
                        '               <div class="label"><label>联系邮箱</label></div>' +
                        '               <div class="body">' + data[0].email + '</div>' +
                        '           </div>' +
                        '       </form>');
                    $('.userInfo').html(html.join(''))
                }
            }
        })
        popup.open('.popup-userInfo');
        $('.popup-userInfo').formLoad({
            userId: data.userId
        })
    }

    var openAuthorityWindow = function (data) {
        // 授权管理 - 弹窗打开
        var administratorIds = data.administratorIds;
        var administratorIdArr = [];
        if (!isBlank(administratorIds)) {
            administratorIdArr = administratorIds.split(",");
        }
        deviceCode = data.deviceCode;
        $('.users').html("");
        App.ajax({
            type: "POST",
            url: context + "/deviceInfo/getDeviceAuthorityUsersList",
            success: function (obj) {
                var code = obj.code;
                if (code == 0) {
                    var data = obj.data;
                    var html = [];
                    for (var i = 0; i < data.length; i++) {
                        var item = data[i];
                        var index = administratorIdArr.indexOf('' + item.userId);
                        if (index >= 0) {
                            html.push('<label style="margin-right:10px;"> <input class="input" type="checkbox" checked="checked" name="administrans" value="' + item.userId + '"> ' + item.realname + ' </label>');
                        } else {
                            html.push('<label style="margin-right:10px;"> <input class="input" type="checkbox" name="administrans" value="' + item.userId + '"> ' + item.realname + ' </label>');
                        }
                    }
                    //$('.users').html(html.join(''))
                    $(".users").initTable(html,4)
                }
            }
        })
        // 表单复制
        $(".popup-device-authority").formLoad({
            deviceCodes: deviceCode
        });
        popup.open(".popup-device-authority")
    }


    $(function () {
        eventEmit();
    })

    function eventEmit() {
        // 设备 - 按钮
        $(document).on('click', '.j-btn-control', function () {
            var state = $(this).data('state');
            var count = 0;
            var deviceCode = ""; // 终端编码
            $('tbody [type="checkbox"]').each(function (index, element) {
                if (element.checked == true) {
                    var data = $(element).parents('tr')[0].dataset;
                    if (count == 0) {
                        deviceCode = data.deviceCode;
                    } else {
                        deviceCode = deviceCode + "," + data.deviceCode;
                    }
                    count++;
                }
            })

            if (count == 0) {
                popup.tipsTop("请先选择数据", 'warning');
                return false;
            }

            switch (Number(state)) {
                case 0: //音量
                    popup.open(".popup-device-sound")
                    // 表单复制
                    $(".popup-device-sound").formLoad({
                        deviceCodeSound: deviceCode
                    });
                    break;
                case 1: //重启
                    restart(deviceCode);
                    break;
                case 3: //设置定时开关机
                    popup.open(".popup-device-power");
                    // 表单复制
                    $(".popup-device-power").formLoad({
                        deviceCodePower: deviceCode
                    });
                    break;
                case 4: //远程关机
                    shutdown(deviceCode, "是否强制关闭设备");
                    break;
                case 5: // 管理授权
                    //获取终端管理可授权人员
                    App.ajax({
                        type: "POST",
                        url: context + "/deviceInfo/getDeviceAuthorityUsersList",
                        success: function (obj) {
                            var code = obj.code;
                            if (code == 0) {
                                var data = obj.data;
                                var html = [];
                                for (var i = 0; i < data.length; i++) {
                                    var item = data[i];
                                    html.push('<label style="margin-right:10px;"> <input class="input" type="checkbox" name="administrans" value="' + item.userId + '"> ' + item.realname + ' </label>');
                                }
                                //$('.users').html(html.join(''))
                                $(".users").initTable(html,4)
                            }
                        }
                    })
                    // 表单复制
                    $(".popup-device-authority").formLoad({
                        deviceCodes: deviceCode
                    });
                    popup.open(".popup-device-authority")
                    break;
                case 6: //SIM卡启用
                    setSimStatus(deviceCode, 0);
                    break;
                case 7: //SIM卡关停
                    setSimStatus(deviceCode, 1);
                    break;
                case 8: //远程关机
                    testNetworkSpeed(deviceCode);
                    break;
            }

        })
    }

    /**
     * 重启
     * @param deviceMac 所选终端的MAC地址
     */
    function restart(deviceCode) {
        var msg = "是否重启设备";
        myConfirm(msg,function(){
            App.ajax({
                type: 'post',
                dataType: 'json',
                url: context + '/deviceInfo/restart',
                data: {deviceCodes: deviceCode},
                cache: false,
                async: true,
                success: function (data) {
                    if ( data.code==0 ) {
                        popup.tipsTop("操作成功", "success");
                        setTimeout(initData(currentPage, pageSize),2000);
                    }else {
                        myAlert(data.msg);
                    }
                }
            });
        });
    }

    /**
     * 定时开关机设置
     */
    function setTimerShutDownOrStart() {
        var deviceCodePower = $('.popup-device-power input[name=deviceCodePower]').val();//终端MAC地址
        var bootTimePower = $('.popup-device-power input[name=bootTimePower]').val(); //开机时间
        var offTimePower = $('.popup-device-power input[name=offTimePower]').val();//关机时间
        if (bootTimePower > offTimePower) {
            myAlert('开机时间应不晚于关机时间');
            return;
        }
        App.ajax({
            type: 'post',
            dataType: 'json',
            url: context + '/deviceInfo/setTimerShutDownOrStart',
            data: {deviceCodes: deviceCodePower, bootTime: bootTimePower, offTime: offTimePower},
            cache: false,
            async: true,
            success: function (data) {
                if ( data.code==0 ) {
                    popup.tipsTop("操作成功", "success");
                    setTimeout(function(){
                        initData(currentPage, pageSize);
                        popup.close();
                    },2000);
                }else {
                    myAlert(data.msg);
                }
            }
        });
    }

    /**
     * 设置音量
     */
    function setVolume() {
        var deviceCodes = $('#deviceCodeSound').val(); //终端mac地址
        var deviceVolume = $('#deviceVolume').val(); //音量
        App.ajax({
            type: 'post',
            dataType: 'json',
            url: context + '/deviceInfo/setVolume',
            data: {deviceCodes: deviceCodes, deviceVolume: deviceVolume},
            cache: false,
            async: true,
            success: function (data) {
                if ( data.code==0 ) {
                    popup.tipsTop("操作成功", "success");
                    setTimeout(function(){
                        initData(currentPage, pageSize);
                        popup.close();
                    },2000);
                }else {
                    myAlert(data.msg);
                }
            }
        });
    }

    /**
     * 远程关机
     * @param deviceCodes 所选终端的唯一编码
     */
    function shutdown(deviceCodes, msg) {
        myConfirm(msg,function(){
            App.ajax({
                type: 'post',
                dataType: 'json',
                url: context + '/deviceInfo/shutdown',
                data: {deviceCodes: deviceCodes},
                cache: false,
                async: true,
                success: function (data) {
                    if ( data.code==0 ) {
                        popup.tipsTop("操作成功", "success");
                        setTimeout(initData(currentPage, pageSize),2000);
                    }else {
                        myAlert(data.msg);
                    }
                }
            });
        });
    }

    /**
     * 管理授权
     */
    function deviceAuthority() {
        // var deviceCodes = $('.popup-device-authority input[name=deviceCodes]').val();//终端编码
        var data = {};
        $.each($(".popup-device-authority form").serializeArray(), function (index, field) {
            if (data[field.name]) {
                data[field.name] += "," + field.value;
            } else {
                data[field.name] = field.value;
            }
        })
        App.ajax({
            type: 'post',
            dataType: 'json',
            url: context + '/deviceInfo/deviceAuthority',
            // data: {deviceCodes: deviceCodes, users: users},
            data: data,
            cache: false,
            async: true,
            success: function (data) {
                if ( data.code==0 ) {
                    popup.tipsTop("操作成功", "success");
                    setTimeout(function(){
                        initData(currentPage, pageSize);
                        popup.close();
                    },2000);
                }else {
                    myAlert(data.msg);
                }
            }
        });
    }

    /**
     * 设置SIM卡状态(0:启用 1:停止)
     */
    function setSimStatus(deviceCodes, simStatus) {
        var msg = "";
        if (simStatus == 0) {
            msg = "启用";
        } else if (simStatus == 1) {
            msg = "关停";
        }
        myConfirm("是否" + msg + "SIM卡",function(){
            App.ajax({
                type: 'post',
                dataType: 'json',
                url: context + '/deviceInfo/setSimStatus',
                data: {deviceCodes: deviceCodes, simStatus: simStatus},
                cache: false,
                async: true,
                success: function (data) {
                    if ( data.code==0 ) {
                        popup.tipsTop("操作成功", "success");
                        setTimeout(initData(currentPage, pageSize),2000);
                    }else {
                        myAlert(data.msg);
                    }
                }
            });
        });
    }

    function checkVolume(i) {
        var volume = $(i).val();
        if (isNaN(volume)) {
            popup.tipsTop("输入格式不正确", "warning");
            $(i).val("");
            return false;
        } else if (volume < 0 || volume > 100) {
            popup.tipsTop("输入格式不正确，请输入0~100");
            $(i).val("");
            return false;
        }
    }

    /**
     * 测速
     * @param deviceCode 所选终端的deviceCode
     */
    function testNetworkSpeed(deviceCode) {
        var msg = "是否对该设备进行测速";
        myConfirm(msg,function(){
            App.ajax({
                type: 'post',
                dataType: 'json',
                url: context + '/deviceInfo/testNetwordSpeed',
                data: {deviceCodes: deviceCode},
                cache: false,
                async: true,
                success: function (data) {
                    if ( data.code==0 ) {
                        popup.tipsTop("操作成功", "success");
                        setTimeout(initData(currentPage, pageSize),2000);
                    }else {
                        myAlert(data.msg);
                    }
                }
            });
        });
    }

    /**
     * 加载线路数据
     * @param currentPage
     * @param pageSize
     */
    var initData = function (loadPageNum, loadPageSize) {
        var params = {
            pageNum: loadPageNum,
            pageSize: loadPageSize,
            machineNumber: $("input[name='machineNumber']").val(),
            propertyName: $("input[name='propertyName']").val(),
            deviceMac: $("input[name='deviceMac']").val(),
            deviceIp: $("input[name='deviceIp']").val(),
            administrator: $("input[name='administrator']").val(),
            district: $("select[name='district']").val(),
            onlineStatus: $("select[name='onlineStatus']").val(),
            deviceStatus: $("select[name='deviceStatus']").val(),
            searchType: $("select[name='searchType']").val(),
            softwareVersion: $("input[name='softwareVersion']").val(),
            firmwareVersion: $("input[name='firmwareVersion']").val()
        };
        App.ajax({
            type: "POST",
            url: context + "/deviceInfo/listdata",
            data: params,
            success: function (obj) {
                var code = obj.code;
                if (code == 0) {
                    //首先清空
                    app.deviceList = [];
                    var data = obj.data;
                    var totalCount = obj.data.total;
                    var html = [];
                    for (var i = 0; i < data.list.length; i++) {
                        var item = data.list[i];
                        app.deviceList.push(item);
                    }
                    app.totalCount = totalCount;
                    renderPage(totalCount, loadPageNum, loadPageSize);
                    iniStatisticsData(params);
                }
            }
        })
        // 设置为中文
        flatpickr.localize(flatpickr.l10ns.zh);
        flatpickr(".ft-hour", {
            enableTime: true,
            noCalendar: true,
            dateFormat: "H:i",
            time_24hr: true
        });
    }

    var initDistrict = function () {
        App.ajax({
            type: "POST",
            url: context + "/deviceInfo/listDistrict",
            success: function (obj) {
                var code = obj.code;
                if (code == 0) {
                    //首先清空
                    app.districtList = [];
                    var data = obj.data;
                    var html = [];
                    for (var i = 0; i < data.length; i++) {
                        var item = data[i];
                        app.districtList.push(item);
                    }
                }
            }
        })
    }

    /**
     * 渲染分页控件化分页
     * @param totalCount
     * @param loadPageIndex
     * @param loadPageSize
     */
    var renderPage = function (totalCount, loadPageIndex, loadPageSize) {
        // 记录当前页码和每页条数
        pageSize = loadPageSize;
        currentPage = loadPageIndex;

        // 控件参数动态替换
        pagination.options.pageIndex = currentPage;
        pagination.options.pageSize= pageSize;
        pagination.options.count= totalCount;
        pagination.render();
    }

    var iniStatisticsData=function(params){
        App.ajax({
            type: "POST",
            url: context + "/deviceInfo/statistics",
            data: params,
            success: function (obj) {
                var code = obj.code;
                if (code == 0) {
                    var data = obj.data;
                    var html = [];
                    app.onLineDeviceCount = data.onLineDeviceCount;
                    app.offLineDeviceCount = data.offLineDeviceCount
                }
            }
        })
    }

    // var onlineStatus = '[[${onlineStatus}]]';
    // var deviceStatus = '[[${deviceStatus}]]';
    // var machineNumber = '[[${machineNumber}]]';
    // var propertyName = '[[${propertyName}]]';
    // var deviceMac = '[[${deviceMac}]]';
    // var administrator = '[[${administrator}]]';
    // var district = '[[${district}]]';
    // var deviceIp = '[[${deviceIp}]]';



    /**
     * 初始化頁面
     */
    $(function () {
        initDistrict();
        initData(currentPage, pageSize);
    });

</script>
</body>
</html>